<template>
  <!-- 表格区域 -->
  <div id="aliasManager" class="list-index">
    <div class="run-box">
      <div class="state-box">
        <div class="run-label">事件审计</div>
      </div>
    </div>
    <div class="table-box">
      <div class="search-bar">
        <div class="main-box">
          <span style="display: flex">
            <div class="event-style">事件类型</div>
            <el-dropdown>
              <span class="el-dropdown-link">
                {{ $t(allEventDefaultValue) }}
                <el-icon class="el-icon--right">
                  <CaretBottom />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu slot="dropdown" class="event-dropdown">
                  <el-dropdown-item @click.native="handleEventChange('所有事件类型')">所有事件类型</el-dropdown-item>
                  <el-dropdown-item v-for="(item, key) in allEventDropDownList" :key="key" @click.native="handleEventChange(item)">
                    {{ $t(item) }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </span>

          <div class="screening-area">
            <div class="btn_setion_time">
              <el-radio-group v-model="radioTime" @change="handleTimeChange">
                <el-radio-button label="最近1天"></el-radio-button>
                <el-radio-button label="最近3天"></el-radio-button>
                <el-radio-button label="最近1周"></el-radio-button>
                <el-radio-button label="自定义时间段" @click="customize"></el-radio-button>
              </el-radio-group>
              <transition name="el-fade-in-linear">
                <span v-if="timePickerShow && radioTime == '自定义时间段'" class="time-picker-style">
                  <p class="searchDescription">请选择日期时间</p>
                  <el-form :model="chosenTime" label-width="70px">
                    <el-form-item label="开始时间">
                      <el-date-picker format="YYYY-MM-DD HH:mm:ss" v-model="chosenTime.startTime" type="datetime" placeholder="选择日期时间"> </el-date-picker>
                    </el-form-item>

                    <el-form-item label="结束时间">
                      <el-date-picker format="YYYY-MM-DD HH:mm:ss" v-model="chosenTime.endTime" type="datetime" placeholder="选择日期时间"> </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" plain @click="dataTimeConfirm" class="timeConfimBtn">确定</el-button>
                    </el-form-item>
                  </el-form>
                </span>
              </transition>
            </div>
          </div>
        </div>
        <div class="refresh">
          <div class="search-box">
            <me-search :search="searchData" :ys="ys" :searchConArr="searchArr" @search="setSearchArr"></me-search>
          </div>
          <el-icon @click="refresh()" class="refreshIcon">
            <RefreshLeft />
          </el-icon>
        </div>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{ background: '#fafafe', color: '#1d1d1f' }"
        :border="true"
        :default-sort="{ prop: 'creation_time', order: 'descending' }"
      >
        <el-table-column label="事件名/ID" class-name="elcell" width="260">
          <template #default="scope">
            <div class="toDetails" @click="showDetails(scope.row)">
              {{ scope.row.name }}
            </div>
            <el-tooltip effect="dark" :content="scope.row.id" placement="bottom">
              <div class="id-box">
                {{ scope.row.id }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="trace_service" label="服务组件" />
        <el-table-column prop="resource_type" label="资源类型">
          <template #default="scope">
            {{ scope.row.resource_type ? $t('resource.' + scope.row.resource_type) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="trace_state" label="事件级别">
          <template #default="scope">
            {{ scope.row.trace_state ? $t(scope.row.trace_state) : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="source_ip" label="来源IP" />
        <el-table-column prop="record_time" label="记录时间" :formatter="timeFormatUTC" width="200" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <div class="actions-box">
              <div class="actions-delete" @click="deleteList(scope.row.name, scope.row.id)" v-if="userType >= 5">删除</div>
              <div class="line" v-if="userType >= 5"></div>
              <div class="actions-delete" @click="showDetails(scope.row)">详情</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="eventData.offset"
        v-model:page-size="eventData.limit"
        :page-sizes="[10, 20, 50, 100]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <transition name="dialog">
      <me-dialog :data="dialogData" v-if="showDialog" :title="dialogName" @close="closeDetails"></me-dialog>
    </transition>
  </div>
</template>

<script lang="ts" setup>
  import appStore from '@/store'
  import moment from 'moment'
  import { timeFormatUTC, timeFormatTZ } from '@/utils/formatter'
  import eventList, { deleteList, eventType, eventBasic } from '@/api/eventAudit'
  import { ref, reactive, computed, onMounted } from 'vue'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import MeSearch from '@/components/Search.vue'
  import MeDialog from './dialog/index.vue'
  let eventAll = {}
  let tableData = ref()
  let timePickerShow = ref(false)
  let tableTotal = ref(0)
  let radioTime = ref('最近1天')
  let allEventDefaultValue = ref('所有事件类型')
  const eventData: eventType = reactive({
    project_id: appStore.userStore.project_id,
    region: appStore.userStore.region,
    event_type: '',
    start_time: '',
    end_time: '',
    offset: 1,
    limit: 10
  })
  const eventLists: deleteList = reactive({
    project_id: appStore.userStore.project_id,
    event_id: ''
  })
  let chosenTime = reactive({
    startTime: '',
    endTime: ''
  })
  let dialogData = reactive({})
  let showDialog = ref(false)
  const showDetails = (row: any) => {
    dialogData = row
    dialogName.value = row.name
    showDialog.value = true
  }
  const dialogName = ref('')
  let startTime = ref()
  let endTime = ref()
  const small = ref(false)
  const disabled = ref(false)
  const background = ref(true)
  const allEventDropDownList = reactive([]) as any
  let searchArr: Array<{ [key: string]: string }> = reactive([])
  let userType = ref()
  userType.value = localStorage.getItem('UserType') as string
  const getEventList = async () => {
    let res = await eventList.getEventList(eventData, eventAll)
    if (res.status === 200) {
      tableData.value = res.data.events
      tableTotal = res.data.total_count
    }
    let dropDownData = reactive({} as { [key: string]: any })
    tableData.value.forEach((item: any) => {
      dropDownData = item
    })
    allEventDropDownList.length = 0
    allEventDropDownList.push(dropDownData.event_type)
  }
  // 事件类型切换
  const handleEventChange = (command: any) => {
    allEventDefaultValue.value = command
    eventData.offset = 1
    if (command === '所有事件类型') {
      Object.assign(eventData, { event_type: '' })
      getEventList()
    } else {
      Object.assign(eventData, { event_type: command })
      getEventList()
    }
  }
  const deleteList = (name: string, id: string) => {
    ElMessageBox.confirm(`确认删除此条数据？\n事件名: ${name}\nID: ${id}  `, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        eventLists.event_id = id
        let res = await eventList.deleteEvent(eventLists)
        if (res.status === 204) {
          ElMessage({
            message: '删除成功！',
            type: 'success'
          })
          getEventList()
        }
      })
      .catch(() => {})
  }

  const ys = {
    id: '事件ID',
    resource_type: '资源类型',
    trace_state: '事件级别'
  }
  let searchData = computed(() => {
    return {
      inputSearch: {
        id: { name: '事件ID' }
      },
      choseSearch: {
        resource_type: {
          name: '资源类型',
          num: 0,
          data: [
            { value: 'fleet', text: 'fleet' },
            { value: 'instance', text: '实例' },
            { value: 'process', text: '进程' },
            { value: 'session', text: '会话' },
            { value: 'build', text: '应用包' },
            { value: 'request', text: '网络请求' }
          ]
        },
        trace_state: {
          name: '事件级别',
          num: 0,
          data: [
            { value: 'NORMAL', text: '正常' },
            { value: 'WARNING', text: '警告' },
            { value: 'INCIDENT', text: '事故' }
          ]
        }
      }
    }
  })
  const setSearchArr = (arr: Array<{ [key: string]: string }>) => {
    searchArr.length = 0
    searchArr.push(...arr)
    let obj: { [key: string]: string } = {}
    searchArr.forEach((item) => {
      let temp_arr = item.value.split(';')
      let value_arr: (string | number)[] = []
      temp_arr.forEach((val) => {
        if (val === '是') {
          value_arr.push(1)
        } else if (val === '否') {
          value_arr.push(0)
        } else {
          value_arr.push(val)
        }
      })
      obj[item.key] = value_arr.join(';')
    })
    eventAll = obj
    eventData.offset = 1
    getEventList()
  }
  const customize = () => {
    timePickerShow.value = true
  }
  // 选择时间事件
  const handleTimeChange = (time: any) => {
    radioTime.value = time
    let now = new Date()
    let past = moment(now)
    if (time == '最近1天') {
      past.subtract(1, 'days')
    } else if (time == '最近3天') {
      past.subtract(3, 'days')
    } else if (time == '最近1周') {
      past.subtract(1, 'weeks')
    } else {
      startTime.value = ''
      endTime.value = ''
      chosenTime.startTime = ''
      chosenTime.endTime = ''
      return
    }
    eventData.offset = 1
    startTime.value = timeFormatTZ(moment(past).utc().format('yyyy-MM-DD HH:mm:ss'))
    endTime.value = timeFormatTZ(moment(now).utc().format('yyyy-MM-DD HH:mm:ss'))
    eventData.start_time = startTime.value
    eventData.end_time = endTime.value
    getEventList()
  }
  // 确认自定义时间选择事件
  const dataTimeConfirm = () => {
    let time1 = new Date(chosenTime.startTime)
    let time2 = new Date(chosenTime.endTime)
    if (time1.getTime() >= time2.getTime()) {
      ElMessage({
        message: '开始时间需小于结束时间',
        type: 'error'
      })
    } else if (chosenTime.startTime !== '' && chosenTime.endTime !== '') {
      startTime.value = timeFormatTZ(moment(chosenTime.startTime).utc().format('yyyy-MM-DD HH:mm:ss'))
      endTime.value = timeFormatTZ(moment(chosenTime.endTime).utc().format('yyyy-MM-DD HH:mm:ss'))
      eventData.start_time = startTime.value
      eventData.end_time = endTime.value
      getEventList()
      timePickerShow.value = false
    } else {
      ElMessage({
        message: '请选择具体时间',
        type: 'error'
      })
    }
  }
  onMounted(() => {
    handleTimeChange('最近1天')
  })
  const handleSizeChange = (val: number) => {
    eventData.limit = val
    eventData.offset = 1
    getEventList()
  }
  const handleCurrentChange = (val: number) => {
    eventData.offset = val
    getEventList()
  }
  const closeDetails = (change: boolean) => {
    showDialog.value = false
    if (change) {
      getEventList()
    }
  }
  const refresh = () => {
    getEventList()
  }
</script>
<style lang="scss" scoped>
  @import '@/assets/scss/list.scss';
  #aliasManager {
    .table-box {
      .search-bar {
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        margin-left: 10px;
        .main-box {
          display: flex;
          .event-style {
            margin-top: 5px;
          }
        }
        .el-dropdown {
          border: 1px solid #e0e2e9;
          width: 150px;
          height: 30px;
          line-height: 30px;
          padding-left: 16px;
          margin: 0 0 20px 10px;
          font-size: 14px;
          font-family: Microsoft YaHei, Microsoft YaHei-Normal;
          color: #252b3a;
          .el-dropdown-link {
            width: 100%;
            display: inline-block;
          }
          .el-icon--right {
            padding-left: 24px;
            color: #8a8e99;
          }
        }
        .screening-area {
          display: flex;
          margin-left: 30px;
          .btn_setion_time {
            position: relative;
            .searchDescription {
              color: $action-color;
              font-size: 14px;
              padding-bottom: 5px;
            }
            .el-radio-group {
              display: flex;
              height: 30px;
              vertical-align: baseline;
              .el-radio-button {
                height: 30px;
              }
            }
            .el-radio-button__inner {
              height: 28px;
              padding: 0 22px !important;
              font-size: 12px;
              line-height: 26px;
              border-color: #fff;
              border-left: 1px solid #e6e6e6;
              vertical-align: baseline;
              background: none;
              &:hover {
                border-color: #0a4cee;
                color: #0a4cee;
                border-radius: 2px;
              }
            }
            .el-radio-button:first-child .el-radio-button__inner {
              border-color: #fff;
              &:hover {
                border-radius: 2px;
                border-color: #0a4cee;
                color: #0a4cee;
              }
            }
            .el-radio-button__orig-radio:checked + .el-radio-button__inner {
              border-radius: 2px;
              color: #0a4cee;
              background-color: #fff;
              border-color: #0a4cee;
              box-shadow: none;
              &:hover {
                color: #0a4cee;
              }
            }
            .el-radio-button:last-child .el-radio-button__inner {
              border-radius: 2px;
            }
            .el-radio-button:focus:not(.is-focus):not(:active):not(.is-disabled) {
              box-shadow: none;
            }
            .time-picker-style {
              position: absolute;
              top: 50px;
              left: 140px;
              border: 1px solid #e6e6e6;
              padding: 20px 20px 0 20px;
              background-color: #fff;
              box-shadow: 0 2px 8px 0 rgba(230, 230, 230, 0.5);
              z-index: 5;
              .timeConfimBtn {
                width: 200px;
                padding: 10px 20px;
                color: #fff;
                background-color: #0a4cee !important;
              }
            }
            .time-text-style {
              color: #0a4cee;
              margin-left: 20px;
              cursor: pointer;
            }
          }
        }
        .refresh {
          display: flex;
          justify-content: space-between;
          .refreshIcon {
            font-size: 16px;
          }
        }
        .search-box {
          width: 600px;
        }
      }
    }
  }
</style>
